package com.ruoyi.web.controller.qcsystem;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.handler.AbstractRowWriteHandler;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.qcsystem.domain.entity.QualityConfirmation;
import com.ruoyi.qcsystem.domain.entity.QualityMoldConfirmation;
import com.ruoyi.qcsystem.service.QcDataService;
import com.ruoyi.qcsystem.service.QcMoldDataService;
import com.ruoyi.ruoyictmanage.domain.entity.Line;
import com.ruoyi.samplemod.domain.entity.Sample;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("qcMoldSystem")
public class QCMoldSystemController {

    @Autowired
    QcMoldDataService qcDataService;
    Integer lineId;
    String startTime;
    String endTime;
    String mpn;
    String lot;

    @GetMapping("list")
    PageInfo<QualityMoldConfirmation> qualityConfirmationList(@RequestParam(defaultValue="6")Integer lineId,
                                                              @RequestParam(defaultValue="1")Integer pageNum,
                                                              @RequestParam(defaultValue="10")Integer pageSize,
                                                              @RequestParam(defaultValue="")String startTime,
                                                              @RequestParam(defaultValue="")String endTime,
                                                              @RequestParam(defaultValue="")String mpn,
                                                              @RequestParam(defaultValue="")String lot
    ){

        if (!startTime.isEmpty() && !endTime.isEmpty()){
            if(startTime.equals(endTime)){
                try {
                    DateTimeFormatter  ft = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                    LocalDate date = LocalDate.parse(endTime,ft);
                    LocalDate nextDay  = date.plusDays(1);
                    endTime = nextDay.format(ft);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        this.lineId = lineId==null?1:lineId;
        this.startTime = startTime==null?"":startTime;
        this.endTime = endTime==null?"":endTime;
        this.mpn = mpn==null?"":mpn;
        this.lot = lot==null?"":lot;
        return qcDataService.qualityConfirmationList(lineId,pageNum,pageSize,startTime,endTime,mpn,lot);
    }


    @PostMapping("addQualityConfirmation")
    int addQualityConfirmation(@Validated  @RequestBody QualityMoldConfirmation qualityConfirmation){
        Long userId = SecurityUtils.getLoginUser().getUserId();
        String userName = SecurityUtils.getLoginUser().getUsername();
        qualityConfirmation.setUserId(userId);
        qualityConfirmation.setAdmit(userName);
        return qcDataService.addQualityConfirmation(qualityConfirmation);
    }

    @DeleteMapping("deleteQualityConfirmation")
    int deleteQualityConfirmation(@RequestParam Long qcId){
        return qcDataService.deleteQualityConfirmation(qcId);
    }

    @GetMapping("getMachineNumber")
    int getMachineNumber(@RequestParam Integer lineId){
        long processId=1;
        return qcDataService.getMachineNumber(lineId,processId);
    }

    @PostMapping("updateQualityConfirmation")
    int updateQualityConfirmation(@Validated @RequestBody QualityMoldConfirmation qualityConfirmation){
        return qcDataService.updateQualityConfirmation(qualityConfirmation);
    }

    @GetMapping("confirmQualityConfirmation")
    int confirmQualityConfirmation(@RequestParam Long qcId){
        String confirmer = SecurityUtils.getLoginUser().getUsername();
        int count= qcDataService.getQualityConfirmationCountByUserId(SecurityUtils.getLoginUser().getUserId(),qcId);
        if (count>0){
            return 0;
        }else {
            return qcDataService.confirmQualityConfirmation(qcId,confirmer);
        }
    }


    @PostMapping("/handleExport")
    public void export(HttpServletResponse response) throws IOException {
        // 1. Set response headers
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("UTF-8");
        String fileName = URLEncoder.encode("样品数据", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        // 2. Get data
        List<QualityMoldConfirmation> dataList = qcDataService.qualityConfirmationList(lineId,startTime,endTime,mpn,lot);

        // 3. Create Excel writer with custom handler
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), QualityMoldConfirmation.class)
                .registerWriteHandler(new AbstractRowWriteHandler() {
                    @Override
                    public void afterRowDispose(WriteSheetHolder writeSheetHolder,
                                                WriteTableHolder writeTableHolder,
                                                Row row,
                                                Integer relativeRowIndex,
                                                Boolean isHead) {
                        // Add timestamp after last data row
                        if (!isHead && relativeRowIndex != null && relativeRowIndex == dataList.size() - 1) {
                            Sheet sheet = writeSheetHolder.getSheet();
                            int lastRowNum = sheet.getLastRowNum();
                            // 创建当前时间
                            Row timeRow = sheet.createRow(lastRowNum + 1);
                            String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                            timeRow.createCell(0).setCellValue("导出时间:"+format);
                            // Merge cells if needed (columns 0-7)
                            sheet.addMergedRegion(new CellRangeAddress(
                                    lastRowNum + 1, // first row
                                    lastRowNum + 1, // last row
                                    0,              // first column
                                    7               // last column
                            ));
                        }
                    }
                })
                .build();

        // 4. Write data
        WriteSheet writeSheet = EasyExcel.writerSheet("样品列表").build();
        excelWriter.write(dataList, writeSheet);
        excelWriter.finish();
    }

    @GetMapping("/getNewMoldDataIfNull")
    Integer getNewMoldDataIfNull(@RequestParam(defaultValue = "") Integer lineId){
        return qcDataService.getNewMoldDataIfNull(lineId);
    }

}
